package map09;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 泛型限定
 * 需求:
 *   1.首先定义三个集合,这三个集合分别存储人,学生,老师
 *   2.再定义一个方法,这个方法可以接收这三个集合
 *     在方法内部遍历集合,在遍历过程中调用吃方法
 *
 *  ? extends E: 泛型上限 限制传入的泛型只能为E类型或者E的子类型
 *  ? super E: 泛型下限  限制传入的泛型只能为E类型或者E的父类型
 */
public class GenericDemo02 {
    public static void main(String[] args) {
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("张三"));
        people.add(new Person("李四"));


        ArrayList<Student> students = new ArrayList<Student>();
        students.add(new Student("流川枫"));
        students.add(new Student("樱木花道"));

        ArrayList<Teacher> teachers = new ArrayList<Teacher>();
        teachers.add(new Teacher("老张"));
        teachers.add(new Teacher("老王"));

        method(people);
        method(students);
        method(teachers);


        ArrayList<Integer> al = new ArrayList<>(Arrays.asList(3, 5, 7));
        //method(al);//ClassCastException: java.lang.Integer cannot be cast to map09.Person
    }

    /*public static void method(ArrayList<?> al) {
        for(Object o : al){//Object o = new Person();
                           //Object o = new Student();
                            //Object o = new Teacher();
                             //Object o = new Integer(3)
             //向下转型
            //Student s = (Student)o;
            //s.eat();
            //Teacher t = (Teacher) o;
            //t.eat();
            Person p = (Person) o; //Person p =new Student();
            p.eat();
        }

    }*/
    public static void method(ArrayList<? extends Person> al) { //限制传入的ArrayList中的泛型为Person或者是Person的子类型
        for (Person p : al){ //遍历Student集合的时候,相当于Person p 指向 Student对象
            p.eat();
        }
    }
}
